package com.idea.relax.log.aspect;

import com.idea.relax.log.props.RelaxLogProperties;
import com.idea.relax.log.support.MethodExecuteResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.util.concurrent.TimeUnit;

/**
 * @author: 沉香
 * @date: 2022/12/24
 * @description: 操作日志的切面
 */
@Slf4j
@AllArgsConstructor
public class ApiLogAspect extends ApiLogSupport implements MethodInterceptor {

    private final RelaxLogProperties properties;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        if (!properties.getApiLog().isEnabled()) {
            return invocation.proceed();
        }
        //目标方法执行状态上下文
        MethodExecuteResult methodExecuteResult = new MethodExecuteResult();
        long startNs = System.nanoTime();
        long time;
        Object result;
        try {
            //执行目标方法
            result = invocation.proceed();
            time = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
            methodExecuteResult.setSuccess(result, time);
        } catch (Throwable ex) {
            time = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
            methodExecuteResult.setError(ex, time);
            throw ex;
        } finally {
            try {
                handleAfterMethod(properties.getApiLog(), invocation, methodExecuteResult);
            } catch (Exception e) {
                log.error("'handleAfterMethod' execution error!", e);
            }
        }
        return result;
    }

}
